package com.glory.hikvisionmobile.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.adapter.EqpWorkLotListAdapter;
import com.glory.hikvisionmobile.base.App;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.bean.EqpWork.EqpLotBean;
import com.glory.hikvisionmobile.bean.EqpWork.EqpLotsBean;
import com.glory.hikvisionmobile.bean.TrackIn.LotInfoBean;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.utils.EditTextEnterUtils;
import com.glory.hikvisionmobile.utils.MyUtils;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class Work_EqpWorkActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {


    @BindView(R.id.etEqpWorkNum)
    FreeUI_ClearEditText etEqpWorkNum;
    @BindView(R.id.rbRun)
    RadioButton rbRun;
    @BindView(R.id.rbWait)
    RadioButton rbWait;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.rvLotList)
    RecyclerView rvLotList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.rbLotID)
    RadioButton rbLotID;
    @BindView(R.id.rbLotNum)
    RadioButton rbLotNum;
    @BindView(R.id.rbPriority)
    RadioButton rbPriority;
    @BindView(R.id.rbRQTime)
    RadioButton rbRQTime;
    @BindView(R.id.rbRecipe)
    RadioButton rbRecipe;
    @BindView(R.id.rbWaitTime)
    RadioButton rbWaitTime;
    @BindView(R.id.rbDeviceDesc)
    RadioButton rbDeviceDesc;
    @BindView(R.id.list_titleLayout)
    RadioGroup listTitleLayout;
    private EqpWorkLotListAdapter eqpWorkLotListAdapter;
    private FreeUI_GeneralFragmentDialog tipDialog;
    private List<String> lotID;
    private String lotType = "WAIT";
    private String holdState;
    private String state;
    private List<EqpLotBean> eqpLotBean;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_eqp_work;
    }

    @Override
    protected void initView() {
        rvLotList.setLayoutManager(new LinearLayoutManager(Work_EqpWorkActivity.this));
        rvLotList.setItemAnimator(new DefaultItemAnimator());
        rvLotList.addItemDecoration(new DividerItemDecoration(Work_EqpWorkActivity.this, 1));
        eqpWorkLotListAdapter = new EqpWorkLotListAdapter(null);
        eqpWorkLotListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        eqpWorkLotListAdapter.isFirstOnly(true);
        rvLotList.setNestedScrollingEnabled(false);
        rvLotList.setAdapter(eqpWorkLotListAdapter);
        lotID = new ArrayList<>();
        listTitleLayout.setOnCheckedChangeListener(this);
        etEqpWorkNum.requestFocus();
        FreeApi_EditTextUtils.setEditTextListener(etEqpWorkNum, this, s -> loadLotList(s, lotType));
        FreeApi_EditTextUtils.setEditTextListener(etLot, this, s -> searchLoy(s));
        EditTextEnterUtils.initEnterToUpperCase(etLot);
        EditTextEnterUtils.initEnterToUpperCase(etEqpWorkNum);
    }


    private void searchLoy(String s) {
        if (s.length() == 0) return;
        if (lotType.equals("WAIT")) {
            if (holdState.equals("On")) {
                showFailDialog("设备不可用，当前设备暂停状态为：" + holdState, getSupportFragmentManager());
                return;
            } else if (!state.equals("RUN") && !state.equals("IDLE")) {
                showFailDialog("设备不可用，当前设备状态为：" + state, getSupportFragmentManager());
                return;
            }
        }
        if (lotID.contains(s)) {
            //跳转进站
            requestDataForNet(s);
        } else {
            showToast("当前批次不在本设备内!", false);
        }
    }

    private void loadLotList(String workNum, String actionType) {
        JsonObject map = new JsonObject();
        map.addProperty("actionType", actionType);
        map.addProperty("equipmentId", workNum);
        NetUtils.requestDara("HIK.PdaTrackByEqp", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<EqpLotsBean>>
                (new TypeToken<BaseResponseBean<EqpLotsBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EqpLotsBean>> response) {
                super.onSuccess(response);
                lotID.clear();
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    EqpLotsBean lots = response.body().getBody();
                    eqpLotBean = lots.getEqpLotBean();
                    holdState = lots.getHoldState();
                    state = lots.getState();
                    eqpWorkLotListAdapter.setNewData(eqpLotBean);
                    eqpWorkLotListAdapter.notifyDataSetChanged();
                    for (EqpLotBean data : eqpLotBean) {
                        lotID.add(data.getLotId());
                    }
                }

            }

            @Override
            public void onError(Response<BaseResponseBean<EqpLotsBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaTrackByEqp");


            }
        });
    }

    private void requestDataForNet(final String lot) {
        JsonObject map = new JsonObject();
        map.addProperty("actionType", "Check");
        map.addProperty("lotId", lot);
        NetUtils.requestDara("HIK.PdaGetLotState", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<LotInfoBean>>(
                new TypeToken<BaseResponseBean<LotInfoBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LotInfoBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    LotInfoBean body = response.body().getBody();
                    startTrackIn(body, lot);

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<LotInfoBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaGetLotState");
            }
        });

    }


    @Override
    protected void initData() {
    }


    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("设备作业");
        return new FreeUI_AddViewEntity("header", llMain);
    }


    @OnClick({R.id.rbRun, R.id.rbWait})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rbRun:
                lotType = "RUN";
                if (etEqpWorkNum.getText().toString().trim().length() == 0) {
                    return;
                }
                loadLotList(etEqpWorkNum.getText().toString().trim(), lotType);
                break;
            case R.id.rbWait:
                lotType = "WAIT";
                if (etEqpWorkNum.getText().toString().trim().length() == 0) {
                    return;
                }
                loadLotList(etEqpWorkNum.getText().toString().trim(), lotType);
                break;
        }
    }

    private void startTrackIn(LotInfoBean lotInfoBean, String s) {
        if (lotInfoBean.getHoldState().equals("On")) {
            showFailDialog("当前状态为hold", getSupportFragmentManager());
            return;
        }

        if (etEqpWorkNum.getText().toString().trim().length() == 0) {
            showToast("设备号不能为空", false);
            etEqpWorkNum.requestFocus();
            return;
        }
        //进站

        if (lotInfoBean.getState().equals("WAIT")) {
            switch (lotInfoBean.getOperationType()) {
                case "DefaultTrackIn":
                case "DieSortingTrackIn":
                case "DieBoundTrackIn":
                    if (actionControl("Work_TrackInActivity", "PDAWorkFragment", "无进站权限"))
                        return;
                    startActivity(Work_TrackInActivity.class, lotInfoBean.getOperationType(), s, etEqpWorkNum.getText().toString().trim());
                    finish();
                    break;
                case "GraphiteBoatTrackIn":
                    if (actionControl("Work_GraphiteBoatTrackInActivity", "PDAWorkFragment", "无石墨舟进站权限"))
                        return;
                    startActivity(Work_GraphiteBoatTrackInActivity.class, lotInfoBean.getOperationType(), s, etEqpWorkNum.getText().toString().trim());
                    finish();
                    break;
                default:
                    showFailDialog("客制化默认进站，PDA暂时无法处理", getSupportFragmentManager());
            }

            //出站

        } else if (lotInfoBean.getState().equals("RUN")) {

            switch (lotInfoBean.getOperationType()) {
                case "DefaultTrackOut":
                    if (actionControl("Work_TrackOutActivity", "PDAWorkFragment", "无普通出站权限"))
                        return;
                    startActivity(Work_TrackOutActivity.class, lotInfoBean.getOperationType(), s, "");
                    finish();
                    break;
                case "GraphiteBoatTrackOut":
                    if (actionControl("Work_GraphiteBoatTrackOutActivity", "PDAWorkFragment", "无石墨舟出站权限"))
                        return;
                    startActivity(Work_GraphiteBoatTrackOutActivity.class, lotInfoBean.getOperationType(), s, "");
                    finish();
                    break;
                case "DieSortingTrackOut":
                    if (actionControl("Work_SortingTrackOutActivity", "PDAWorkFragment", "无分选出站权限"))
                        return;
                    startActivity(Work_SortingTrackOutActivity.class, lotInfoBean.getOperationType(), s, "");
                    finish();
                    break;
                case "DieBoundTrackOut":
                    if (actionControl("Work_PatchTrackOutActivity", "PDAWorkFragment", "无贴片出站权限"))
                        return;
                    startActivity(Work_PatchTrackOutActivity.class, lotInfoBean.getOperationType(), s, "");
                    finish();
                    break;
                default:
                    showFailDialog("客制化默认出站，PDA暂时无法处理", getSupportFragmentManager());
            }


        } else {
            showFailDialog("当前批次状态为" + lotInfoBean.getState() + ",无法进站", getSupportFragmentManager());
        }

    }


    private void startActivity(Class<? extends Activity> activity, String lotType, String lotNum, String devices) {
        Bundle bundle = new Bundle();
        bundle.putString("lotType",lotType);
        bundle.putString("lotNum",lotNum);
        bundle.putString("devices",devices);
        FreeApi_Utils.skipWithExtraIntent("header",bundle,Work_EqpWorkActivity.this,activity);
    }

    private void showFailDialog(String message, FragmentManager fragmentManager) {
        tipDialog = FreeApi_DialogUtils.getConfirmDialog(App.app, "确定", message, () -> {

        });
        tipDialog.show(fragmentManager, "EQPWORKDIALOG");
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i1) {
        if (eqpLotBean == null){
            return;
        }
        int childCount = listTitleLayout.getChildCount();
        for (int i = 0; i < childCount; i++) {
            RadioButton radioButton = (RadioButton) listTitleLayout.getChildAt(i);
            if (radioButton.isChecked()){
                List<EqpLotBean> lotsBeans = MyUtils.sortList(eqpLotBean, i);
                if (lotsBeans.size() == eqpLotBean.size()){
                    eqpWorkLotListAdapter.setNewData(lotsBeans);
                }else {
                    eqpWorkLotListAdapter.setNewData(eqpLotBean);
                }
                radioButton.setTextColor(getResources().getColor(R.color.red));
            }else {
                radioButton.setTextColor(getResources().getColor(R.color.black));
            }
        }
    }
}
